package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.JPanel;

import model.Database;
import model.DeviceTableModel;
import model.IOFile;
import model.OptionMessenger;
import model.UICommand;
import ui.BusyDialog;
import view.DevicePanel;

public class DeviceController implements ActionListener {
	private DevicePanel view;
	private DeviceTableModel tableModel;

	public DeviceController(DeviceTableModel tableModel) {
		this.tableModel = tableModel;
		this.view = new DevicePanel(tableModel, this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();
		switch (cmd) {
		case "id":
		case "name":
		case "type":
		case "date":
		case "provider":
		case "amount":
			view.setEditable(cmd);
			break;
		case "schFid":
			view.setTextID();
			break;
		case "search":
			search();
			break;
		case UICommand.SAVE_CMD:
			view.stopCellEditing();
			BusyDialog.showBusyDialog(OptionMessenger.windowForComponent(view),
					"Đang lưu dữ liệu", new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent e) {
							tableModel.save();
						}
					}, null);
			break;
		case UICommand.RELOAD_CMD:
			ActionListener action = new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent arg0) {
					try {
						Thread.sleep(1000);
						tableModel.loadData("SELECT * FROM device");
					} catch (InterruptedException e) {
						e.printStackTrace(IOFile.getInstance());
					}
				}
			};
			BusyDialog.showBusyDialog(OptionMessenger.windowForComponent(view),
					"Tải lại dữ liệu", action, null);
		}
	}

	public void search() {
		Connection conn;
		PreparedStatement pre = null;
		try {
			conn = Database.connect();

			if (view.isSelectedGroup()) { // check query
				pre = conn.prepareStatement(createSQL());
			} else { // search field
				pre = conn
						.prepareStatement("SELECT * FROM device WHERE id LIKE ?");
				pre.setString(1, "%".concat(view.getSearchText()).concat("%"));
			}

			tableModel.loadData(pre);
		} catch (ClassNotFoundException e) {
			e.printStackTrace(IOFile.getInstance());
		} catch (SQLException e) {
			e.printStackTrace(IOFile.getInstance());
		}
	}

	public String createSQL() {
		StringBuilder sql = new StringBuilder("SELECT * FROM device WHERE ");
		ArrayList<Object[]> column = view.getQuery();
		for (int i = 0; i < column.size(); i++) {
			if (i != 0)
				sql.append(" AND ");
			sql.append(column.get(i)[0]);
			sql.append(column.get(i)[1]);
			sql.append(column.get(i)[2]);
		}
		return sql.toString();
	}

	public JPanel getView() {
		return this.view;
	}
}